<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { AdminParams } from '@/types/admin'
import { ElNotification } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { login } from '@/api/admin'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()
const formRef = ref<FormInstance>()
const ruleForm = ref<AdminParams>({
  username: '',
  password: ''
})
const loading = ref<boolean>(false)
// 表单校验规则
const rules = ref<FormRules<AdminParams>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码必须是6-16位的字符', trigger: 'blur' }
  ]
})
// 登录按钮 自定义校验规则
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      const res = await login(ruleForm.value)
      userStore.setUserInfo(res.data)
      ElNotification({
        title: '温馨提示',
        message: '登录成功',
        type: 'success',
        duration: 1500
      })
      setTimeout(() => {
        router.replace({
          path: '/'
        })
      }, 500)
    }
  })
}
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <el-form
        size="large"
        autocomplete="off"
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            :prefix-icon="User"
            v-model="ruleForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            :prefix-icon="Lock"
            type="password"
            show-password
            v-model="ruleForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="btn"
            :loading="loading"
            @click="submitForm(formRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.login-page {
  height: 100vh;
  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 50%,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .btn {
      width: 100%;
      margin-top: 16px;
    }
  }
}
</style>
@/api/admin
